import os
import sys
import time
import traceback
from concurrent.futures.thread import ThreadPoolExecutor
from core import config
from u2 import Device, add_provider, GlobalDeviceInfo
from u2.exceptions import DeviceOfflineError

import requests

# 在线
onlines = {}
# 正在使用的
taskings = []


def start(before_todo, todo, ips: list=None):

    # 设置控制台(黑块)标题
    os.system('title ' + sys.modules['__main__'].__file__)

    if ips is None:
        ips = [config.agc_provider_prefix + suffix for suffix in config.agc_provider_suffix if suffix]
    print(ips)
    threads = ThreadPoolExecutor(len(config.agc_provider_suffix) * 500)
    add_provider(map(lambda x: (x, 8888), ips))

    # 执行自定义统一操作
    before_todo()

    while True:
        online_info = GlobalDeviceInfo.get_online()
        # print('Online info:', online_info)
        for udid, ip, port in online_info:
            if ip.startswith('172.18.0'):
                continue
            if udid not in taskings:
                taskings.append(udid)
                threads.submit(todo_wrapper, todo, udid).add_done_callback(
                    lambda future: taskings.remove(future.result()))
        time.sleep(0.3)


def todo_wrapper(todo, udid):
    try:
        if udid in onlines:
            d = onlines[udid]
        else:
            d = Device(udid)
            onlines[udid] = d
        todo(d)
    except DeviceOfflineError:
        print(udid, 'DeviceOffline.')
        if udid in onlines:
            onlines.pop(udid)
    except:
        print(udid, '*' * 20, '\n', traceback.format_exc())
    finally:
        return udid
